<template>
  <el-dialog :title="form.brandId ? '编辑' : '新增'" v-model="visible"
             :close-on-click-modal="false" draggable style="width: 450px">
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="120px" v-loading="loading">
      <el-form-item label="选择车系" prop="series">
        <el-select v-model="form.series" placeholder="选择车系" clearable class="input-width">
          <el-option
              v-for="item in series"
              :key="item.key"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandName">
        <el-input v-model="form.brandName" class="input-width"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="4"
            class="input-width"
        />
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="CarBrandDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/yu/carBrand'
import { rule } from '/@/utils/validate';
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 定义字典
const { series } = useDict('series');
// 提交表单数据
const form = reactive({
  brandId:'',
  brandName: '',
  series: '',
  remark: '',
});

// 定义校验规则
const dataRules = ref({
  brandName: [{required: true, message: '品牌名不能为空', trigger: 'blur'}],
  series: [{required: true, message: '车系不能为空', trigger: 'blur'}]
})

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.brandId = ''

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取carBrand信息
  if (id) {
    form.brandId = id
    getcarBrandData(id)
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;

  try {
    loading.value = true;
    form.brandId ? await putObj(form) : await addObj(form);
    useMessage().success(form.brandId ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getcarBrandData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>

<style scoped>
  .input-width {
    width: 200px !important;
  }
</style>